<template>
  <view class="container page-container">
    <!-- 订单状态选项卡 -->
    <view class="tabs">
      <view class="tab-item" v-for="(tab, index) in tabs" :key="index" :class="{ active: currentTab === index }"
        @click="switchTab(index)">
        <text>{{ tab }}</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list" @scrolltolower="loadMore" refresher-enabled
      :refresher-triggered="refreshing" @refresherrefresh="onRefresh" :style="{ height: 'calc(100vh - 120rpx)' }"
      :lower-threshold="100">
      <view v-if="filteredOrders.length > 0">
        <view class="order-item" v-for="order in filteredOrders" :key="order.id" @click="goToOrderDetail(order.id)">
          <view class="order-header">
            <view class="merchant-info">
              <image class="merchant-logo" :src="order.merchantLogo" mode="aspectFill"></image>
              <text class="merchant-name">{{ order.merchantName }}</text>
            </view>
            <text class="order-status" :class="getStatusClass(order.status)">{{ order.statusText }}</text>
          </view>
          <text class="delivery-time" v-if="order.deliveryTime">预计{{ formatTime(order.deliveryTime) }}送达</text>

          <view class="order-goods">
            <view class="goods-item" v-for="(item, index) in order.goods" :key="index">
              <image class="goods-image" :src="item.image" mode="aspectFill"></image>
              <view class="goods-info">
                <text class="goods-name">{{ item.name }}</text>
                <text class="goods-specs" v-if="item.specifications">
                  {{ formatSpecifications(item.specifications) }}
                </text>
              </view>
              <view class="goods-price-info">
                <text class="goods-quantity">x{{ item.quantity }}</text>
                <text class="goods-price">¥{{ item.subtotal.toFixed(2) }}</text>
              </view>
            </view>
          </view>

          <view class="order-footer">
            <view class="order-time">
              <text>{{ formatDate(order.createTime) }}</text>
            </view>
            <view class="order-price">
              <text class="price-label">实付</text>
              <text class="price-value">¥{{ order.actualPay.toFixed(2) }}</text>
            </view>
          </view>

          <view class="order-actions">
            <view class="action-btns">
              <button class="action-btn" v-if="order.status === 1 || order.status === 2" @click.stop="showCancelModal(order.id)">取消订单</button>
              <button class="action-btn" v-if="order.status === 1" @click.stop="payOrder(order.id)">去支付</button>

              <button class="action-btn primary" v-if="order.status === 4" @click.stop="reorder(order.id)">再来一单</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image class="empty-icon" src="/static/icons/empty-order.svg" mode="aspectFit"></image>
        <text class="empty-text">暂无相关订单</text>
        <button class="go-shopping-btn" @click="goShopping">去逛逛</button>
      </view>

      <!-- 加载更多 -->
      <view class="loading-more" v-if="loading && filteredOrders.length > 0">
        <text>加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && filteredOrders.length > 0">
        <text>没有更多订单了</text>
      </view>
    </scroll-view>

    <!-- 取消订单原因选择弹窗 -->
    <CancelOrderModal 
      :visible="cancelModalVisible" 
      @cancel="handleCancelModalClose" 
      @confirm="handleCancelConfirm" 
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { formatTime } from '@/utils/time.js';
import { getOrderPage, cancelOrder as cancelUserOrder } from '@/api/order.js';
import { getGoodsListByOrderId } from "@/api/goods.js";
import { useCartStore } from '@/store/cart.js';
import CancelOrderModal from '@/components/CancelOrderModal.vue';

const tabs = ['全部', '待付款', '待接单', '配送中', '已完成', '已取消'];
const currentTab = ref(0);
const orders = ref([]);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const hasMore = ref(true);
const refreshing = ref(false);
const cartStore = useCartStore();
const cancelModalVisible = ref(false); // 取消订单弹窗显示状态
const currentCancelOrderId = ref(''); // 当前要取消的订单ID

const formatSpecifications = (specsStr) => {
  try {
    const specs = JSON.parse(specsStr);
    if (!Array.isArray(specs)) return specsStr;
    return specs.map(spec => spec.value).join(',');
  } catch (e) {
    return specsStr; // 如果不是JSON格式，直接返回原字符串
  }
};

const filteredOrders = computed(() => {
  if (currentTab.value === 0) {
    return orders.value;
  } else {
    const statusMap = {
      1: 1, // 待付款
      2: 2, // 待接单
      3: 3, // 配送中
      4: 4, // 已完成
      5: 5  // 已取消
    };
    return orders.value.filter(order => order.status === statusMap[currentTab.value]);
  }
});

const loadOrders = async () => {
  loading.value = true;

  try {
    const res = await getOrderPage({
      pageNo: page.value,
      pageSize: pageSize.value,
      ...(currentTab.value === 0 ? {} : { status: currentTab.value })
    });

    if (page.value === 1) {
      orders.value = res.data.list;
    } else {
      orders.value = [...orders.value, ...res.data.list];
    }

    hasMore.value = res.data.total > orders.value.length;
  } catch (e) {
    console.error('获取订单列表失败', e);
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const switchTab = (index) => {
  currentTab.value = index;
  page.value = 1;
  loadOrders();
};

const loadMore = () => {
  console.log('loadMore', page.value, hasMore.value, loading.value);
  if (!hasMore.value || loading.value) return;

  page.value++;
  loadOrders();
};

const onRefresh = () => {
  refreshing.value = true;
  page.value = 1;

  // 重新加载数据
  setTimeout(() => {
    loadOrders();
    refreshing.value = false;
  }, 1000);
};

onMounted(() => {
  console.log('开始加载订单数据');
  loadOrders();
});

onShow(() => {
  // 获取存储的订单状态值
  const status = uni.getStorageSync('orderListStatus');
  if (status) {
    currentTab.value = status;
    uni.removeStorageSync('orderListStatus'); // 使用后清除状态值
  }
});

const formatDate = (dateStr) => {
  // 将日期字符串转换为iOS支持的格式
  const formattedStr = dateStr.replace(' ', 'T');
  const date = new Date(formattedStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

const getStatusClass = (status) => {
  const classMap = {
    1: 'status-pending',
    2: 'status-processing',
    3: 'status-delivering',
    4: 'status-completed',
    5: 'status-canceled'
  };
  return classMap[status] || '';
};

const goToOrderDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/detail?id=${orderId}`
  });
};

/**
 * 显示取消订单弹窗
 */
const showCancelModal = (orderId) => {
  currentCancelOrderId.value = orderId
  cancelModalVisible.value = true
}

/**
 * 关闭取消订单弹窗
 */
const handleCancelModalClose = () => {
  cancelModalVisible.value = false
  currentCancelOrderId.value = ''
}

/**
 * 确认取消订单
 */
const handleCancelConfirm = async (cancelReason) => {
  try {
    uni.showLoading({ title: '处理中...' });
    await cancelUserOrder(currentCancelOrderId.value, cancelReason);
    
    uni.showToast({
      title: '订单已取消',
      icon: 'success'
    });
    
    // 关闭弹窗
    cancelModalVisible.value = false
    currentCancelOrderId.value = ''
    
    // 重新加载订单列表
    page.value = 1;
    loadOrders();
  } catch (e) {
    console.error('取消订单失败', e);
    uni.showToast({
      title: '取消订单失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
}

const payOrder = (orderId) => {
  uni.showLoading({
    title: '正在支付'
  });

  setTimeout(() => {
    uni.hideLoading();

    // 模拟支付成功
    const orderIndex = orders.value.findIndex(order => order.id === orderId);
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = 2;
      orders.value[orderIndex].statusText = '待接单';
      orders.value[orderIndex].payTime = new Date().toLocaleString();

      uni.showToast({
        title: '支付成功',
        icon: 'success'
      });
    }
  }, 1500);
};



const reorder = async (orderId) => {
  uni.showLoading({ title: '处理中...' });
  try {
    // 获取商品列表
    const orderGoodsVoListRes = await getGoodsListByOrderId(orderId);
    const orderGoodsVoList = orderGoodsVoListRes.data;
    //遍历goodsList
    for (const orderGoodsVo of orderGoodsVoList) {
      const selectedSpecifications = [];
      if (orderGoodsVo.orderGoods.specifications) {
        const specifications = JSON.parse(orderGoodsVo.orderGoods.specifications);
        for (const spec of specifications) {
          selectedSpecifications.push({
            name: spec.name,
            value: spec.value,
            price: spec.price
          });
        }
      }
      // 添加到购物车
      cartStore.addToCart(orderGoodsVo.goods, selectedSpecifications, orderGoodsVo.orderGoods.quantity);
    }
    
  } catch (e) {
    console.error('添加到购物车失败', e);
    uni.showToast({
      title: '添加到购物车失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
  uni.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
    // 跳转到商家页面
    const order = orders.value.find(order => order.id === orderId);
    setTimeout(() => {
      uni.navigateTo({
        url: `/pages/merchant/detail?id=${order.merchantId}`
      });
    }, 1500);
};

const goShopping = () => {
  uni.switchTab({
    url: '/pages/index/index'
  });
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #fafafa;
  background-image: linear-gradient(to bottom, #fff8f8, #fafafa);
  display: flex;
  flex-direction: column;
}

.tabs {
  display: flex;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 24rpx 0;
  position: sticky;
  top: 0;
  z-index: 10;
  border-radius: 0 0 24rpx 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);

  .tab-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
    padding-bottom: 12rpx;
    transition: all 0.3s ease;

    &.active {
      color: #ff6b6b;
      font-weight: 600;
      transform: scale(1.05);

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 32rpx;
        height: 4rpx;
        background: linear-gradient(to right, #ff9a9e, #ff6b6b);
        border-radius: 4rpx;
      }
    }
  }
}

.order-list {
  flex: 1;
  padding: 24rpx;
  box-sizing: border-box;
  width: 100%;
}

.order-item {
  background-color: #fff;
  border-radius: 24rpx;
  margin: 0 0 30rpx 0;
  padding: 36rpx;
  box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.04), 0 2rpx 6rpx rgba(0, 0, 0, 0.02);
  width: 100%;
  box-sizing: border-box;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
  overflow: hidden;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #f5f5f5;

  .merchant-info {
    display: flex;
    align-items: center;

    .merchant-logo {
      width: 64rpx;
      height: 64rpx;
      border-radius: 16rpx;
      margin-right: 18rpx;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
    }

    .merchant-name {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
    }
  }

  .order-status {
    font-size: 26rpx;
    padding: 6rpx 16rpx;
    border-radius: 24rpx;

    &.status-pending {
      color: #ff8c00;
      background-color: rgba(255, 140, 0, 0.1);
    }

    &.status-processing {
      color: #1989fa;
      background-color: rgba(25, 137, 250, 0.1);
    }

    &.status-delivering {
      color: #07c160;
      background-color: rgba(7, 193, 96, 0.1);
    }

    &.status-completed {
      color: #323233;
      background-color: rgba(50, 50, 51, 0.05);
    }

    &.status-canceled {
      color: #969799;
      background-color: rgba(150, 151, 153, 0.1);
    }
  }
}

.order-goods {
  margin: 24rpx 0;

  .goods-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .goods-image {
      width: 120rpx;
      height: 90rpx;
      border-radius: 16rpx;
      margin-right: 20rpx;
      flex-shrink: 0;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
      object-fit: cover;
    }

    .goods-info {
      flex: 1;
      overflow: hidden;

      .goods-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 8rpx;
        font-weight: 500;
      }

      .goods-specs {
        font-size: 24rpx;
        color: #999;
        background-color: #f9f9f9;
        padding: 4rpx 10rpx;
        border-radius: 8rpx;
        display: inline-block;
      }
    }

    .goods-price-info {
      text-align: right;
      flex-shrink: 0;
      margin-left: 16rpx;

      .goods-quantity {
        font-size: 24rpx;
        color: #999;
        margin-right: 8rpx;
      }

      .goods-price {
        font-size: 28rpx;
        color: #333;
        font-weight: 600;
      }
    }
  }
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 24rpx;
  border-top: 2rpx solid #f8f8f8;

  .order-time {
    font-size: 24rpx;
    color: #999;
  }

  .order-price {
    .price-label {
      font-size: 24rpx;
      color: #999;
      margin-right: 8rpx;
    }

    .price-value {
      font-size: 32rpx;
      color: #ff6b6b;
      font-weight: 600;
    }
  }
}

.order-actions {
  margin-top: 24rpx;

  .action-btns {
    display: flex;
    justify-content: flex-end;
    flex-wrap: wrap;
    gap: 20rpx;

    .action-btn {
      padding: 12rpx 28rpx;
      font-size: 26rpx;
      border-radius: 28rpx;
      line-height: 1.4;
      margin: 0;
      transition: all 0.3s ease;

      // 取消订单按钮
      &:nth-child(1) {
        background-color: #fff;
        border: 1px solid #ff6b6b;
        color: #ff6b6b;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.1);

        &:active {
          background-color: rgba(255, 107, 107, 0.05);
        }
      }

      // 去支付按钮
      &:nth-child(2) {
        background: linear-gradient(to right, #ff9a9e, #ff6b6b);
        color: #fff;
        border: none;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.2);

        &:active {
          box-shadow: 0 2rpx 6rpx rgba(255, 107, 107, 0.15);
        }
      }

      // 确认收货按钮
      &[v-if*="status === 3"] {
        background: linear-gradient(to right, #ff9a9e, #ff6b6b);
        color: #fff;
        border: none;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.2);

        &:active {
          box-shadow: 0 2rpx 6rpx rgba(255, 107, 107, 0.15);
        }
      }

      // 再来一单按钮
      &.primary {
        background: linear-gradient(to right, #ff9a9e, #ff6b6b);
        color: #fff;
        border: none;
        font-weight: 500;
        box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.2);

        &:active {
          box-shadow: 0 2rpx 6rpx rgba(255, 107, 107, 0.15);
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;

  .empty-icon {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
    opacity: 0.8;
  }

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 40rpx;
    letter-spacing: 2rpx;
  }

  .go-shopping-btn {
    padding: 18rpx 50rpx;
    font-size: 28rpx;
    color: #fff;
    background: linear-gradient(to right, #ff9a9e, #ff6b6b);
    border-radius: 40rpx;
    border: none;
    box-shadow: 0 6rpx 16rpx rgba(255, 107, 107, 0.3);
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.2);
    }
  }
}

.loading-more,
.no-more {
  text-align: center;
  padding: 30rpx 0;
  font-size: 26rpx;
  color: #999;
  letter-spacing: 2rpx;
}

.no-more {
  position: relative;

  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 80rpx;
    height: 2rpx;
    background-color: #eee;
  }

  &::before {
    right: calc(50% + 40rpx);
  }

  &::after {
    left: calc(50% + 40rpx);
  }
}
</style>
